package com.jackrain.nea.web.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.schema.Column;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.core.schema.TriggerHolder;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.service.Handle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QueryUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Slf4j
@RestController
@Api(value = "CommandController", description = "单对象事务处理")
public class CommandController {

    @ApiOperation(value="单对象保存", notes="param:{\n" + "  \"objid\":123||-1,\n" + "  \"fixcolumn\": {\n" + "    \"C_STORE\": {\n" + "      \"NAME\": \"沧州 \",\n" + "      \"CODE\": \"00009\"\n" + "    },\n" + "    \"C_STOREITEM\": [\n" + "      {\n" + "\"ID\": -1,\n" + "        \"AMT\": 100\n" + "      },\n" + "      {\n" + "\"ID\": 2,\n" + "        \"AMT2\": 3456\n" + "      }\n" + "    ]\n" + "  }\n" + "}\n")
    @RequestMapping(path = "/p/cs/objectSave", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doSave(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "data", required = true) String data,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder valueHolder = new ValueHolder();

        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);
            
            if(objid<0){            
                 throw new NDSException("objid -1");
            }

            JSONObject fixcolumn= JSON.parseObject(data);
            
            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("fixcolumn",fixcolumn);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");
            
            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject()); 
            }
            
            DefaultWebEvent event = new DefaultWebEvent("doSave", request, false);
            
            event.put("param", jor);
            
            valueHolder= Handle.process(jor,qsession,event,"save");


            valueHolder.put("message", Resources.getMessage("保存成功",qsession.getLocale()));
            
            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
        
    }
    
    @ApiOperation(value="单对象新增")
    @RequestMapping(path = "/p/cs/objectAdd", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doAdd(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "data", required = true) String data,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder valueHolder = new ValueHolder();

        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);

//            if(objid<0){
//                throw new NDSException("objid -1");
//            }

            JSONObject fixcolumn= JSON.parseObject(data);

            //增加界面不显示字段默认值传入，识别第6位
            ArrayList columns = table.getColumns(new int[]{6}, false,-1);

            columns.forEach(item->{
                fixcolumn.put(((Column)item).getName(),((Column)item).getDefaultValue());
            });

            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("fixcolumn",fixcolumn);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doAdd", request, false);

            event.put("param", jor);

            valueHolder= Handle.process(jor,qsession,event,"add");
            
            int code=Tools.getInt(String.valueOf(valueHolder.get("code")),0);
             
            if(code==0) {
                valueHolder.put("message", Resources.getMessage("保存成功", qsession.getLocale()));
            }
            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }


    @ApiOperation(value="单对象删除")
    @RequestMapping(path = "/p/cs/objectDelete", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doDelete(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "data", required = false) String data,@RequestParam(value = "command", required = false) String command,@RequestParam(value = "isdelmtable", required = false,defaultValue = "true") String isdelmtable) throws Exception {
        ValueHolder valueHolder = new ValueHolder();
        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);

            if(objid<0){
                throw new NDSException("objid -1");
            }
            
            JSONObject tabitem= JSON.parseObject(data);
            
            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            if(tabitem!=null){
                jor.put("tabitem",tabitem); 
            }
            jor.put("table",table.getName());
            jor.put("isdelmtable",Tools.getBoolean(isdelmtable,true));


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doDelete", request, false);

            event.put("param", jor);

            valueHolder= Handle.process(jor,qsession,event,"delete");
            
            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }

    @ApiOperation(value="单对象提交")
    @RequestMapping(path = "/p/cs/objectSubmit", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doSubmit(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder valueHolder = new ValueHolder();
        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);

            if(objid<0){
                throw new NDSException("objid -1");
            }

            //JSONObject fixcolumn= JSON.parseObject(data);

            
            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doSubmit", request, false);

            event.put("param", jor);

            valueHolder= Handle.process(jor,qsession,event,"submit");

            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }

    @ApiOperation(value="单对象作废")
    @RequestMapping(path = "/p/cs/objectVoid", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doVoid(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder valueHolder = new ValueHolder();
        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);

            if(objid<0){
                throw new NDSException("objid -1");
            }

            //JSONObject fixcolumn= JSON.parseObject(data);


            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doVoid", request, false);

            event.put("param", jor);

            valueHolder= Handle.process(jor,qsession,event,"void");

            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }

    @ApiOperation(value="单对象反提交")
    @RequestMapping(path = "/p/cs/objectUnSubmit", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doUnSubmit(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objid", required = true) Long objid,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder valueHolder = new ValueHolder();
        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");

            QuerySession qsession = QueryUtils.createQuerySession(userWeb);

            TableManager tm = qsession.getTableManager();

            Table table = tm.getTable(tablename);

            objid = Tools.getLong(objid, -1);

            if(objid<0){
                throw new NDSException("objid -1");
            }

            //JSONObject fixcolumn= JSON.parseObject(data);


            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doUnSubmit", request, false);

            event.put("param", jor);

            valueHolder= Handle.process(jor,qsession,event,"unsubmit");

            return valueHolder.toJSONObject();

        }catch (Exception e) {
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("message", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }

    @ApiOperation(value="批量删除")
    @RequestMapping(path = "/p/cs/batchDelete", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doBatchDelete(HttpServletRequest request,
                                    @RequestParam(value = "table", required = true) String tablename,
                                    @RequestParam(value = "objids", required = true) String objids,
                                    @RequestParam(value = "command", required = false) String command,
                                    @RequestParam(value = "isdelmtable", required = false,defaultValue = "true") String isdelmtable) throws Exception {
        ValueHolder result = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        Table table = tm.getTable(tablename);
        String[] ids = objids.split(",");

        JSONArray errJa = new JSONArray();

        for(int i=0; i<ids.length; i++){
            JSONObject errJo = new JSONObject();
            Long objid = Tools.getLong(ids[i], -1);
            if(objid < 0){
                continue;
            }
            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());
            jor.put("isdelmtable",Tools.getBoolean(isdelmtable,true));

            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");
            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doDelete", request, false);
            event.put("param", jor);

            try{
                ValueHolder valueHolder= Handle.process(jor,qsession,event,"delete");
                if(valueHolder.get("code") != null){
                    int code = (int)valueHolder.get("code");
                    if(code < 0){
                        errJo.put("objid",objid);
                        errJo.put("message",valueHolder.get("message"));
                        errJa.add(errJo);
                    }
                }
            }catch(Exception e){
                log.error(e.getMessage(),e);
                errJo.put("objid",objid);
                errJo.put("message",e.getMessage());
                errJa.add(errJo);
            }
        }

        if(errJa.size() > 0){
            result.put("code",-1);
            result.put("data",errJa);
            result.put("message","删除成功记录数："+ (ids.length-errJa.size())+"，删除失败记录数："+errJa.size());
        }else{
            result.put("code",0);
            result.put("message","删除成功记录数："+ ids.length);

        }

        return result.toJSONObject();

    }

    @ApiOperation(value="批量提交")
    @RequestMapping(path = "/p/cs/batchSubmit", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doBatchSubmit(HttpServletRequest request,
                                    @RequestParam(value = "table", required = true) String tablename,
                                    @RequestParam(value = "objids", required = true) String objids,
                                    @RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder result = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        Table table = tm.getTable(tablename);

        String[] ids = objids.split(",");

        JSONArray errJa = new JSONArray();

        for(int i=0; i<ids.length; i++){
            JSONObject errJo = new JSONObject();
            Long objid = Tools.getLong(ids[i], -1);
            if(objid < 0){
                continue;
            }

            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());

            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doSubmit", request, false);
            event.put("param", jor);

            try{
                ValueHolder valueHolder= Handle.process(jor,qsession,event,"submit");
                if(valueHolder.get("code") != null){
                    int code = (int)valueHolder.get("code");
                    if(code < 0){
                        errJo.put("objid",objid);
                        errJo.put("message",valueHolder.get("message"));
                        errJa.add(errJo);
                    }
                }
            }catch(Exception e){
                log.error(e.getMessage(),e);
                errJo.put("objid",objid);
                errJo.put("message",e.getMessage());
                errJa.add(errJo);
            }
        }

        if(errJa.size() > 0){
            result.put("code",-1);
            result.put("data",errJa);
            result.put("message","提交成功记录数："+ (ids.length-errJa.size())+"，提交失败记录数："+errJa.size());
        }else{
            result.put("code",0);
            result.put("message","提交成功记录数："+ ids.length);
        }

        return result.toJSONObject();

    }

    @ApiOperation(value="批量作废")
    @RequestMapping(path = "/p/cs/batchVoid", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doBatchVoid(HttpServletRequest request, @RequestParam(value = "table", required = true) String tablename, @RequestParam(value = "objids", required = true) String objids,@RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder result = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        Table table = tm.getTable(tablename);


        String[] ids = objids.split(",");

        JSONArray errJa = new JSONArray();

        for(int i=0; i<ids.length; i++){
            JSONObject errJo = new JSONObject();
            Long objid = Tools.getLong(ids[i], -1);
            if(objid < 0){
                continue;
            }

            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());

            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");

            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doVoid", request, false);
            event.put("param", jor);

            try{
                ValueHolder valueHolder= Handle.process(jor,qsession,event,"void");
                if(valueHolder.get("code") != null){
                    int code = (int)valueHolder.get("code");
                    if(code < 0){
                        errJo.put("objid",objid);
                        errJo.put("message",valueHolder.get("message"));
                        errJa.add(errJo);
                    }
                }
            }catch(Exception e){
                log.error(e.getMessage(),e);
                errJo.put("objid",objid);
                errJo.put("message",e.getMessage());
                errJa.add(errJo);
            }
        }

        if(errJa.size() > 0){
            result.put("code",-1);
            result.put("data",errJa);
            result.put("message","作废成功记录数："+ (ids.length-errJa.size())+"，作废失败记录数："+errJa.size());
        }else{
            result.put("code",0);
            result.put("message","作废成功记录数："+ ids.length);

        }

        return result.toJSONObject();
    }

    @ApiOperation(value="批量反提交")
    @RequestMapping(path = "/p/cs/batchUnSubmit", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject doBatchUnSubmit(HttpServletRequest request,
                                      @RequestParam(value = "table", required = true) String tablename,
                                      @RequestParam(value = "objids", required = true) String objids,
                                      @RequestParam(value = "command", required = false) String command) throws Exception {
        ValueHolder result = new ValueHolder();
        UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        Table table = tm.getTable(tablename);

        String[] ids = objids.split(",");
        JSONArray errJa = new JSONArray();

        for(int i=0; i<ids.length; i++){
            JSONObject errJo = new JSONObject();
            Long objid = Tools.getLong(ids[i], -1);
            if(objid < 0){
                continue;
            }
            JSONObject jor=new JSONObject();
            jor.put("objid",objid);
            jor.put("table",table.getName());


            TriggerHolder.VersionedTrigger trigger=table.getTrigger("TRI");
            if(trigger!=null){
                jor.put("aspecttrigger",trigger.toJSONObject());
            }

            DefaultWebEvent event = new DefaultWebEvent("doUnSubmit", request, false);
            event.put("param", jor);

            try{
                ValueHolder valueHolder= Handle.process(jor,qsession,event,"unsubmit");
                if(valueHolder.get("code") != null){
                    int code = (int)valueHolder.get("code");
                    if(code < 0){
                        errJo.put("objid",objid);
                        errJo.put("message",valueHolder.get("message"));
                        errJa.add(errJo);
                    }
                }
            }catch(Exception e){
                log.error(e.getMessage(),e);
                errJo.put("objid",objid);
                errJo.put("message",e.getMessage());
                errJa.add(errJo);
            }
        }

        if(errJa.size() > 0){
            result.put("code",-1);
            result.put("data",errJa);
            result.put("message","反提交成功记录数："+ (ids.length-errJa.size())+"，反提交失败记录数："+errJa.size());
        }else{
            result.put("code",0);
            result.put("message","反提交成功记录数："+ ids.length);

        }

        return result.toJSONObject();
    }
    
    
    

}